import React, { useState, useEffect } from 'react';
import { Drawer, Descriptions, Steps, Popover, Card, StepProps } from 'antd';
import { ColumnsType } from 'antd/lib/table';
import { GridContent } from '@ant-design/pro-layout';
import AGrid from '@/components/SelfComp/AGrid';
import { CqDetailItem, CqTradeItem } from '@/types/cq';
import { DataItem, FlagEnum, FormDrawerProps } from '@/types/global';
import { getItemValue } from '@/utils/commons';
import { dateFormat } from '@/utils/utils';

type ViewCqProps<T> = FormDrawerProps<T> & {
  flag?: FlagEnum
  cqStatusData: DataItem[];
}

const columns: ColumnsType<CqTradeItem> = [
  {
    title: '交易功能码',
    dataIndex: 'funcCode',
    width: 200
  },
  {
    title: '交易名称',
    dataIndex: 'funcName',
    ellipsis: true,
  },
  {
    title: '交易路径',
    dataIndex: 'funcAction',
    ellipsis: true,
  },
  {
    title: '已分配任务数量',
    dataIndex: 'taskNum',
    width: 200
  },
];

/**
 * 展示需求详细信息，若已分配交易，则展示交易列表
 * 
 * @param props 
 * @returns 
 */
const ViewCqDrawer: React.FC<ViewCqProps<CqDetailItem>> = (props) => {
  // 自定义分页
  const [trades, setTrades] = useState<CqTradeItem[]>([]);
  const [total, setTotal] = useState<number>(0);
  const [pageSize, setPageSize] = useState<number>(10);

  useEffect(() => {
    console.info('ViewCqProps.useEffect');
    // 获取用户列表
    const { formData } = props;
    const { tradeList } = formData;
    fetchTradeByPage(1, pageSize, tradeList);
  }, []);

  const onClose = () => {
    // 先清除form表单
    const {onHandlerCancel} = props;
    if (onHandlerCancel) {
      onHandlerCancel();
    }
  }

  /**
   * 表格勾选回调函数
   * @param {*} rows 表格选中数据集合
   */
  const onSelectRow = (keys: React.Key[], rows: CqTradeItem[]) => {
    // 暂无作用
  };

  /**
   * 手动获取分页数据
   * @param {*} pageSize 每页记录条数
   * @param {*} pageNum 页码
   * @param {*} userList 用户列表数据
   */
  const fetchTradeByPage = (pageNum: number, pageSize: number, tradeList: CqTradeItem[]) => {
    if (tradeList && tradeList.length > 0) {
      setPageSize(pageSize);
      const tmpTradeList: CqTradeItem[] = tradeList.slice((pageNum - 1) * pageSize, pageNum * pageSize);
      setTrades(tmpTradeList);
      setTotal(tradeList.length);
    }
  }

  /**
   * 页码改变的回调，参数是改变后的页码及每页条数
   * @param page 改变后的页码，上送服务器端
   * @param pageSize 每页数据条数
   */
  const onPageNumAndSizeChange = (page: number, pageSize: number) => {
    console.log(page, pageSize);
    const { formData } = props;
    const { tradeList } = formData;
    fetchTradeByPage(page, pageSize, tradeList);
  };

  const { formData, drawerWidth, drawerVisible, cqStatusData } = props;
  const { status = '', testFlag } = formData;
  const cqStatus = getItemValue(cqStatusData, status);
  const cqStatusStr = `${status}-${cqStatus}`;
  const testFlagStr = !testFlag ? '非配合测试' : '配合测试';
  // console.info(`flag: ${flag}`);
  const code = 'cq-view';
  const loading = false;
  const rowKey = (record: CqTradeItem) => record.tradeId;
  const pkField = 'tradeId';
  const customDot = (
    dot: React.ReactNode,
    {
      status,
    }: {
      status: string;
    },
  ) => {
    if (status === 'process') {
      return (
        <Popover placement="topLeft" arrowPointAtCenter content={cqStatusStr}>
          {dot}
        </Popover>
      );
    }
    return dot;
  };

  const stepItems = cqStatusData.filter(item => item.key !== '0').map((item) => {
    const description = `${item.key}-${item.value}`;
    const stepItem: StepProps = {
      title: item.value,
      description
    }
    return stepItem;
  });

  return (
    <Drawer
      open={drawerVisible}
      title="需求详情"
      placement="right"
      width={drawerWidth}
      onClose={onClose}
    >
      <GridContent>
        <Card title='流程进度' style={{ marginBottom: 16, backgroundColor: '#C5EBC9' }}>
          <Steps
            direction={'horizontal'}
            progressDot={customDot}
            current={parseInt(status) - 1}
            items={stepItems}
          />
        </Card>
        <Card title='需求基本信息' style={{ marginBottom: 16, backgroundColor: '#C5EBC9' }}>
          <Descriptions>
            <Descriptions.Item label="需求编号">{formData.cqCode}</Descriptions.Item>
            <Descriptions.Item label="需求名称" span={2}>{formData.cqName}</Descriptions.Item>
            <Descriptions.Item label="所属系统">{formData.systemCode}</Descriptions.Item>
            <Descriptions.Item label="所属集群">{formData.clstCode}</Descriptions.Item>
            <Descriptions.Item label="所属应用">{formData.appCode}</Descriptions.Item>
            <Descriptions.Item label="是否配合测试">{testFlagStr}</Descriptions.Item>
            <Descriptions.Item label="主开人员">{formData.auditor}</Descriptions.Item>
            <Descriptions.Item label="设计人员">{formData.designerA}</Descriptions.Item>
            <Descriptions.Item label="需求状态">{cqStatusStr}</Descriptions.Item>
            <Descriptions.Item label="投产日期">{dateFormat(formData.prdDate)}</Descriptions.Item>
          </Descriptions>
        </Card>
        <Card title='需求日期信息' style={{ marginBottom: 16, backgroundColor: '#C5EBC9' }}>
          <Descriptions column={2}>
            <Descriptions.Item label="DEV开始时间">{dateFormat(formData.devStartDate)}</Descriptions.Item>
            <Descriptions.Item label="DEV结束时间">{dateFormat(formData.devEndDate)}</Descriptions.Item>
            <Descriptions.Item label="SIT开始时间">{dateFormat(formData.sitStartDate)}</Descriptions.Item>
            <Descriptions.Item label="SIT结束时间">{dateFormat(formData.sitEndDate)}</Descriptions.Item>
            <Descriptions.Item label="UAT开始时间">{dateFormat(formData.uatStartDate)}</Descriptions.Item>
            <Descriptions.Item label="UAT结束时间">{dateFormat(formData.uatEndDate)}</Descriptions.Item>
          </Descriptions>
        </Card>
        <Card title='需求文档信息' style={{ marginBottom: 16, backgroundColor: '#C5EBC9' }}>
          <Descriptions column={1}>
            <Descriptions.Item label="需求文件路径">{formData.srdPath}</Descriptions.Item>
            <Descriptions.Item label="概设文件路径">{formData.odsPath}</Descriptions.Item>
            <Descriptions.Item label="详设文件路径">{formData.ddsPath}</Descriptions.Item>
            <Descriptions.Item label="接口分析结果路径">{formData.oarPath}</Descriptions.Item>
          </Descriptions>
        </Card>
        <Card title='需求交易列表' style={{ marginBottom: 16, backgroundColor: '#C5EBC9' }}>
          <AGrid
            code={code}
            noActionColumn={true}
            columns={columns}
            rowKey={rowKey}
            pkField={pkField}
            dataSource={trades}
            loading={loading}
            total={total}
            scroll={{x:1000}}
            onSelectRow={onSelectRow}
            onPageNumAndSizeChange={onPageNumAndSizeChange}
          />
        </Card>
      </GridContent>
    </Drawer>
  );
}

export default ViewCqDrawer;